package com.andyliu.controller;

import com.andyliu.common.ResponseResult;
import com.andyliu.interceptor.BusinessType;
import com.andyliu.log.Log;
import com.andyliu.system.entity.User;
import com.andyliu.system.service.IUserService;
import com.andyliu.util.DateUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

/**
 * ClassName: LoginController
 * Description: TODO
 * date: 2021/8/9 9:27 上午
 *
 * @author andyliu
 * @qq 115176513
 * @since JDK 1.8
 */
@Controller
@ApiIgnore
public class LoginController {

    @Autowired
    private IUserService userService;
    @PostMapping("/login")
    @ResponseBody
    @Log(moduleName = "用户登录",businessType = BusinessType.GRANT,isSaveParam = true)
    public ResponseResult login(@RequestBody User user, String code, HttpServletResponse response){
        UsernamePasswordToken token = new UsernamePasswordToken(user.getLoginName(),user.getPassword());
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            user = userService.getUserByLoginName(user.getLoginName());
            String jwtToken = JWT.create().withAudience(user.getUserId().toString()).withExpiresAt(DateUtil.getTokenExpressTime())
                    .sign(Algorithm.HMAC256(user.getPassword()));
            Cookie cookie  = new Cookie("token",jwtToken);
            response.addCookie(cookie);
            response.addHeader("author",jwtToken);
            return ResponseResult.success("登陆成功",jwtToken);
        }catch (UnknownAccountException ex){
            return ResponseResult.error("用户名不存在");
        }catch (IncorrectCredentialsException ex){
            return  ResponseResult.error("密码不正确");
        }catch (LockedAccountException ex){
            return ResponseResult.error("账户以锁定，请稍后重试");
        }catch (ExpiredCredentialsException ex){
            return ResponseResult.error("凭证过期");
        }
    }

    @GetMapping("index")
    @Log(moduleName = "主页",businessType = BusinessType.OTHER,isSaveParam = false)
    public String toIndex(){
        return "index";
    }

    @GetMapping("main")
    public String main(){
        return "main";
    }

    @GetMapping("logout")
    public String logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "redirect:/index.html";
    }
}
